package com.bjtang.book.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjtang.book.dto.IdDto;
import com.bjtang.book.dto.ReturnDto;
import com.bjtang.book.entiy.PictureTable;
import com.bjtang.book.myexception.DataCheckException;
import com.bjtang.book.service.MyService;
import com.bjtang.book.service.PictureService;
import com.bjtang.book.util.ReturnUtil;
import com.bjtang.book.util.StringUtil;
import com.bjtang.book.util.UUID生成器;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @类名 PictureController.java
 * @说明 图床控制器
 * @作者 唐帮杰
 * @时间 2019年7月19日下午5:21:36
 */
@Api(tags = "图床综合管理")
@Validated
@RestController
@RequestMapping(value = "/picture/")
public class PictureController {
	@Autowired
	PictureService pictureService;
	@Autowired
	MyService myService;

	@ApiOperation("上传/新建图片批量")
	@PostMapping("/")
	public ReturnDto PictureUploads(@RequestParam("file") List<MultipartFile> pictures) throws IOException {

		System.err.println(pictures.size());
		List<String> urlList = new ArrayList<String>();

		for (int i = 0; i < pictures.size(); i++) {
			// String pictureName = pictures.get(i).getOriginalFilename();
			// 过滤特殊字符 " . " 除外
			String pictureName = StringUtil.filtration(pictures.get(i).getOriginalFilename());
			String uuid = UUID生成器.generateUUID();
//			String picturePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/static/图库/"
//					+ uuid + pictureName;
			// String picturePath = "/home/bj-tang/img/" + uuid + pictureName;
			String picturePath = "/img/" + uuid + pictureName;
			pictures.get(i).transferTo(new File(picturePath));

			PictureTable pictureTable = new PictureTable();
			pictureTable.setPictureName(pictureName);
			pictureTable.setPicturePath(uuid + pictureName);
			pictureTable.setFounder(myService.getMyselfId());
			pictureService.save(pictureTable);

			urlList.add(uuid + pictureName);
		}
		return ReturnUtil.success(urlList);
	}

	@ApiOperation("删除指定图片")
	@DeleteMapping("/")
	public ReturnDto deletePictureById(@RequestBody @Valid IdDto pictureNumber) {
		// 先查询是否有记录,是否有操作权限,再进行删除数据库记录,最后删除物理文件
		PictureTable byId = pictureService.getById(pictureNumber.getId());
		if (byId == null)
			throw new DataCheckException("图片没找到");
		if (byId.getFounder().longValue() != myService.getMyselfId().longValue())
			throw new DataCheckException("没有操作权限");
		boolean removeById = pictureService.removeById(pictureNumber.getId());
		if (removeById) {
			// String picturePath =
			// ClassUtils.getDefaultClassLoader().getResource("").getPath() +
			// "static/static/图库/"
			// + byId.getPicturePath();
			// String picturePath = "/home/bj-tang/img/" + byId.getPicturePath();
			String picturePath = "/img/" + byId.getPicturePath();
			File file = new File(picturePath);
			if (file.exists() && file.isFile())
				file.delete();
			return ReturnUtil.success();
		}

		return ReturnUtil.error();
	}

	@ApiOperation("查询图片列表ByUserPage")
	@GetMapping("/by-user/{userId}/{current}/{size}")
	public ReturnDto GetArticleByUser(@PathVariable Long userId, @PathVariable Long current, @PathVariable Long size) {
		Page<PictureTable> page = new Page<PictureTable>(current, size);
		return ReturnUtil.success(pictureService.lambdaQuery().eq(PictureTable::getFounder, userId)
				.orderByDesc(PictureTable::getPictureNumber).page(page));
	}

//	@ApiOperation("管理员删除指定图片ByUrl")
//	@DeleteMapping("/by-url/")
//	public ReturnDto deletePictureByUrl(@RequestBody String url) {
//		// 先查询是否有记录,再进行删除数据库记录,最后删除物理文件
//		List<PictureTable> list = pictureService.lambdaQuery().eq(PictureTable::getPicturePath, url).list();
//		if (list.size() == 0)
//			throw new DataCheckException("图片没找到");
//
//		boolean removeById = pictureService.removeById(list.get(0).getPictureNumber());
//		if (removeById) {
//			// String picturePath =
//			// ClassUtils.getDefaultClassLoader().getResource("").getPath() +
//			// "static/static/图库/"
//			// + url;
//			// String picturePath = "/home/bj-tang/img/" + url;
//			String picturePath = "/img/" + url;
//			File file = new File(picturePath);
//			if (file.exists() && file.isFile())
//				file.delete();
//			return ReturnUtil.success();
//		}
//		return ReturnUtil.error();
//	}
}
